package wang.chuangen.session.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * java原生序列化工具类
 * @author 王传根
 * @date 2016-5-13上午9:13:37
 */
public class JavaByteSerialization implements Serialization{
	
	@Override
	public byte[] toObjectByte(Object data) throws IOException {
		if(data==null)return null;
		ByteArrayOutputStream bos=new ByteArrayOutputStream();
		ObjectOutputStream oos=null;
		try {
			oos=new ObjectOutputStream(new BufferedOutputStream(bos));
			oos.writeObject(data);
			oos.flush();
			bos.flush();
			return bos.toByteArray();
		} finally {
			if(oos!=null){
				oos.close();
			}
			bos.close();
		}
	}

	@Override
	public Object parseObjectByte(byte[] data) throws IOException, ClassNotFoundException {
		if(data==null || data.length==0)return null;
		ByteArrayInputStream bis=new ByteArrayInputStream(data);
		ObjectInputStream ois=null;
		try {
			ois=new ObjectInputStream(new BufferedInputStream(bis));
			return ois.readObject();
		} finally {
			if(ois!=null){
				ois.close();
			}
			bis.close();
		}
	}

}
